<?php
/**
 * Name: cartnew.php
 * Desc: This class is designed to provide a basic, extendable framework for an eCommerce backend.
 *
 * Version: 1.5
 *
 * Date:    (Revised) May 30, 2007 and many more
 * Author:  Christopher J. Burdick 
 *
 **/
include('dbconfig.inc.php');

$conn=mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

/*
 * This function is designed to create a shopping cart.  AKA, it just retrieves the session_id() from
 * the current user and adds it to the database if it is not already in there.
 *
 * @param 		sessionid 		=   Session ID of the user
 */
    function createcart($sessionid){
        $result=mysql_query("SELECT id, datemodified, subtotal, itemsincart, session_id from modx_ecomm_cart_header where session_id=\"$sessionid\"");
        $headerinfo = mysql_fetch_row($result);
        $dat = date("D M j G:i:s T Y");
		
		if ($sessionid != $headerinfo[4]){
            $result=mysql_query("INSERT into modx_ecomm_cart_header (session_id, dateadded) values (\"$sessionid\", \"$dat\")") or die ('Add Header Failed: ' . mysql_error());
	        $result=mysql_query("SELECT id, session_id from modx_ecomm_cart_header where session_id=\"$sessionid\"");
    	    $headerinfo = mysql_fetch_row($result);
        }
		return $headerinfo;
    }

/*
 *  This function is designed to add an item to a user's cart.
 *
 *  @param 		id   		=   SKU of the item
 *  @param 		sessionid	=	Session ID of the user
 *  @param 		opts     	=   Options associative array to store options, this is obtained from the post
 *								and then passed to us when this method is called from ModX
 *  @param 		qty      	=   Item Quantity
 */
    function addtocart($id, $sessionid, $opts, $qty ){		
        $qty = $qty > 0 ? $qty : 1;
		$hdrinfo = createcart($sessionid);
		
		// Check to make sure cart was created

       	$dat = date("D M j G:i:s T Y");
     
		$itincart = intval($hdrinfo[3]);
		
		// Get options pricing
		$optionsreturn=getoptionspricing($opts, $id, $qty);

		$result = mysql_query("SELECT amount from modx_ecomm_items where id=$id");
   		$item= mysql_fetch_row($result);
		
        if (isset($id)){
			$result = mysql_query("SELECT id, quantity, options, optionsprice, totalprice from modx_ecomm_cart_detail where header_id=$hdrinfo[0] and item_id=$id");
			
			$flag=false;
			$num = mysql_num_rows($result);
			for ($k=0; $k < $num; $k++){
				$res = mysql_fetch_row($result);
				if ($res[2]==$optionsreturn['optstring']){
					$itincart++;
					$quantity=$res[1] + $qty;	
  	    	    	$prc= floatval($item[0]);
			
    	    	    $newprc=floatval($hdrinfo[2]) + ($prc * $qty) + floatval($optionsreturn['price']);
					
					$optsprice=floatval($res[3]) + floatval($optionsreturn['price']);
					$totalprice = floatval($res[4]) + floatval($prc) + floatval($optionsreturn['price']);
					$result=mysql_query("UPDATE modx_ecomm_cart_detail set quantity=$quantity, optionsprice=$optsprice, totalprice=$totalprice where header_id=" . $hdrinfo[0] . " and id=" . $res[0]) or die ("UPDATE DETAIL: " . mysql_error());
	    	    	$result = mysql_query("UPDATE modx_ecomm_cart_header set datemodified=\"$dat\", itemsincart=$itincart, subtotal=$newprc where id=$hdrinfo[0]") or die ("Update header ERROR: " . mysql_error());
					$flag=true;
				}
			}
					
			if ($flag==false){
				 // In case there was already one in the cart but the options were NOT equal...add new record
				$itincart++;
   	   	   		$result = mysql_query("SELECT amount from modx_ecomm_items where id=$id") or die ("Get Product ID Error: " . mysql_error());
    	   		$item= mysql_fetch_row($result);
		   		$prc= floatval($item[0]);
				$totalprice = floatval($prc) + floatval($optionsreturn['price']);
	           	$newprc=floatval($hdrinfo[2]) + ($prc * $qty) + floatval($optionsreturn['price']);
	    	   	$result = mysql_query("UPDATE modx_ecomm_cart_header set datemodified=\"$dat\", itemsincart=$itincart, subtotal=$newprc where id=$hdrinfo[0]") or die ("Update header ERROR: " . mysql_error());
		       	$result=mysql_query("INSERT INTO modx_ecomm_cart_detail (header_id, item_id, quantity, date, options, optionsprice, totalprice) values ($hdrinfo[0], $id, $qty, \"$dat\", \"" . addslashes($optionsreturn['optstring']) . "\", " . floatval($optionsreturn['price']) . ", $totalprice)") or die ("Add Cart Detail Error:" . mysql_error());
            	$result=mysql_query("SELECT id FROM modx_ecomm_cart_detail where header_id=$hdrinfo[0] and item_id=$id") or die ("Get Cart Detail: " . mysql_error());
            	$detail_id=mysql_fetch_row($result);
			}
		}
		
		$quant=getitemcount($sessionid);
		
		$cartNotifier= isset($quant) ? "You have " . $quant : "You have 0 items in your shopping Cart!";
	    if ($quant > 1) {
           $cartNotifier .= " items in your shopping cart totaling: $" . floatval($newprc);
        }  else if ($quant == 1) {
           $cartNotifier .= " item in your shopping cart totaling: $" . floatval($newprc);
        }
		$cartNotifier .= "<br />";
		$cartNotifier .= "<a href=\"index.php?id=4002&sessionid=$sessionid\">View Cart</a>";
	    return $cartNotifier;
	}



/*
 * This function is designed to take an encoded string of options and adjust the item price appropriately
 * 
 * @param	opts		=	encoded string of the options selected on the website
 * @param	id			=	ID of the item we are adding (mysql id)
 * @param	qty			=	qty so we can figure the total options pricing
 */
	function getoptionspricing($opts, $id, $qty){
		// Init Vars
		$ret['price']=0;
		$ret['optstring']="";
		
		// Break opts passed from site into an array
		$splitopts = explode("||||", $opts);

		for ($i=0; $i < sizeof($splitopts); $i++){
			//Split name of option from value
			$splitnameval=explode("::::", $splitopts[$i]);
			
			// Store Option Name
			$optsfromsite[$i][0] = $splitnameval[0];
			
			// Store value(s) chosen by customer
			$optsfromsite[$i][1] = $splitnameval[1];
			
			// Get Option Render just so we know what to do to get all values and what to return to the user.
			$optinfo = getoptionbyname($optsfromsite[$i][0]);
			
			/* It is important to check, as we don't want to obtain options from a TEXT 
			 * or TEXT Area and we only need to loop through multiple options for 
			 * a CHECK or SELECT
			 */
			if ($optinfo['renderas']=="CHECK" || $optinfo['renderas']=="MULTI"){
				// checkbox and multi selects send info as id;;;;id;;;;id;;;; etc...
				$optsvalsplit=explode(";;;;", $optsfromsite[$i][1]);	
				$flag = false;
				$first = true;
			
				for ($j=0; $j < sizeof($optsvalsplit); $j++){
					//Just in case they choose no options
					if ($optsvalsplit[$j]!=""){
						$optproperties = getlistoptionproperties($optsvalsplit[$j]);
						$ret['price'] = $ret['price'] + (floatval($optproperties['offset']) * $qty);
						if ($first==true){
							$optsvalname=getlistoptionproperties($optsvalsplit[$j]);
							$ret['optstring'] .= $optsfromsite[$i][0] . ": " . $optsvalname['name'];
							$first=false;
						} else {
							$optsvalname=getlistoptionproperties($optsvalsplit[$j]);
							$ret['optstring'] .= ", " . $optsvalname['name'];
						}
						$flag=true;
					} else {
						if ($flag==false){
							$ret['optstring'] .= $optsfromsite[$i][0] . ": None"; 							
						}
					}
				}
				$ret['optstring'] .= "<br />";
			} else if ($optinfo['renderas']=="SELECT" || $optinfo['renderas']=="RADIO"){
	            $optproperties = getlistoptionproperties($optsfromsite[$i][1]);
				$ret['price'] = $ret['price'] + (floatval($optproperties['offset']) * $qty);
				$ret['optstring'] .= $optsfromsite[$i][0] . ": " . $optproperties['name'] . "<br />"; 				
		 	} else if ($optinfo['renderas']=="TEXT" || $optinfo['renderas']=="TEXTAREA"){
				$ret['optstring'] .= $optsfromsite[$i][0] . ": " . $optsfromsite[$i][1] . "<br />"; 
			}
		}
		return $ret;
	}

/*
 * This function is designed to handle loading the data for a particular item from the audit table.
 * 
 * @param 	id		=	itemid
 */
	function getitemproperties($id){
		$qry = "SELECT id, content_id, sku, name, fullname, description, amount, oversized, hazmat, disabled, shoppingenabled, quoteenabled, status from modx_ecomm_items_audit where id=$id";
		$result=mysql_query($qry) or die ("MYSQL FIND ITEM ERROR: " . mysql_error());
		$row=mysql_fetch_row($result);
		
		$itemprops['id'] = $row[0];
		$itemprops['content_id'] = $row[1];
		$itemprops['sku'] = $row[2];
		$itemprops['name'] = $row[3];
		$itemprops['fullname'] = $row[4];
		$itemprops['amount'] = $row[6];
		$itemprops['oversized'] = $row[7];
		$itemprops['hazmat'] = $row[8];
		$itemprops['disabled'] = $row[9];
		$itemprops['shoppingenabled'] = $row[10];
		$itemprops['quoteenabled'] = $row[11];
		$itemprops['status'] = $row[12];

		$qry = "SELECT template, content, longtitle, description from modx_site_content where id=" . $itemprops['content_id'];
		$result=mysql_query($qry) or die ("MYSQL GET CONTENT INFO ERROR: " . mysql_error());
		$row=mysql_fetch_row($result);
		
		$itemprops['pagetemplate'] = $row[0];
		$itemprops['contentarea'] =  $row[1];
		$itemprops['longtitle'] = $row[2];
		$itemprops['description'] = $row[3];

		return $itemprops;
	}

/**
 * This function is designed to handle updating an items options in modx_ecomm_items_options
 * 
 * @param		itemid		=	The ID of the item to update
 * @param		chosenopts	=	The ID's of the chosen options for an item
 */
	function updateitemoptions($itemid, $chosenopts){
		// Delete all options first
		$qry = 'DELETE from modx_ecomm_items_options where item_id=' . $itemid;
		mysql_query($qry);
		
		// Read new options
		for ($i=0; $i < sizeof($chosenopts); $i++){
			$qry = 'INSERT into modx_ecomm_items_options (options_id, item_id) values (' . $chosenopts[$i]. ', ' . $itemid . ')';
			mysql_query($qry);
		}
	}

/**
 * This function is designed to handle item page updates.  If the ID is 0, it is new...if the ID is >0 it means the page is being updated
 * 
 * @param	itemid				= MySQL ID of the item to be edited  (NOTE:  if 0, it indicates that the item is new)
 * @param	itemname			= Name of the Item
 * @param	shortdescription	= Longer description of the item (but still short)
 * @param	contentarea			= The main templated content area
 * @param	price				= Price of the Item
 * @param	hazmat				= Hazmat fee for shipping
 * @param	oversized			= Oversized shipping fee
 * @param	status				= Audit Status =>  Whether the item is updated, new, etc.  This is mostly for use by Blackbird...our open source ESB offering
 * 								  for QuickBooks integration
 * @param	active				= Tells whether the item is active or inactive
 * @param	enablequote			= Is the quote basket enabled?
 * @param	template			= Overall page template
 * @param	enableshop			= Is the Shopping Cart enabled for this item?
 */
	function updatepage($itemid, $itemname, $shortdescription, $contentarea, $price, $hazmat, $oversized, $status, $active, $enablequote, $template, $enableshop){
		if ($enableshop=='true'){$enableshop = 1;}else{$enableshop = 0;}
		if ($enablequote=='true'){$enablequote = 1;}else{$enablequote = 0;}
		if ($active=='true'){$active= 0;}else{$active=1;}
		if ($itemid == 0){ // New Item			
			$itemid=writeitemtodb($itemid, $itemname, $shortdescription, $price, $hazmat, $oversized, $enableshop, $enablequote, $active, "NEW");

			//Config - Probably shouldn't touch too much here...perhaps template a
			$parent= 4008;
            $richtext= 1;
            $searchable= 1;
            $cacheable= 0;
            $published= 1;

            $contentid = addcontainer($itemid, $itemid, $contentarea, $itemname, $shortdescription, $shortdescription, $published, $parent, $richtext, $template, $searchable, $cacheable, $itemname);
			
			// add container id to the item in the database (for easy update and retrieval of the correct site content			
			$qry = "update modx_ecomm_items set content_id=$contentid where id=$itemid";
			$result=mysql_query($qry);
			$qry = "update modx_ecomm_items_audit set content_id=$contentid where items_id=$itemid";
			$result=mysql_query($qry);
		}else { // Updated Item
			$itemid=writeitemtodb($itemid, $itemname, $shortdescription, $price, $hazmat, $oversized, $enableshop, $enablequote, $active, "UPDATED");
			$qry  = "SELECT content_id from modx_ecomm_items_audit where items_id=$itemid";
			$result=mysql_query($qry) or die ("MYSQL FIND CONTENT ID ERROR: " . mysql_error());
			$row=mysql_fetch_row($result);
			$contentid=$row[0];

			//Update Container Page
			$qry  = "UPDATE modx_site_content set ";
			$qry .= "pagetitle=\"$itemname\", ";
			$qry .= "longtitle=\"$itemname\", ";
			$qry .= "description=\"$shortdescription\", ";
			$qry .= "template=$template, ";
			$qry .= "content=\"$contentarea\", ";
			$qry .= "menutitle=\"$itemname\" ";
			$qry .= "where id=$contentid";
			
			$result=mysql_query($qry) or die ("MYSQL UPDATE SITE CONTENT PAGE: " . mysql_error());
		}
	}

/*
 *  This function is used for updating a cart item.  If the quantity is set to zero it will delete, otherwise it will update the item record.
 *
 *  @param 		sku	     		=   SKU of the item
 *  @param 		sessionid    	=   Session ID of the user
 *  @param 		qty          	=   Item Quantity 
 *  @param 		opts			=	Options which were chosen with the item
 *  @param 		detailid		= 	The detailid is included to make sure we delete or update the correct item from the user's cart 
 * 
 */
    function updateitem($sessionid, $sku, $qty, $opts, $detailid){
        $result = mysql_query("SELECT id from modx_ecomm_cart_header where session_id=\"$sessionid\"");
        $header_id = mysql_fetch_row($result);
        
		$result = mysql_query("SELECT id from modx_ecomm_items where sku=\"$sku\"");
        $item_id = mysql_fetch_row($result);
		
		$options=encodeoptions($opts, $item_id[0]);
        
		$dat= date("D M j G:i:s T Y");
        
		if ( $qty == 0 ){
            $result=mysql_query("DELETE FROM modx_ecomm_cart_detail where header_id=\"$header_id[0]\" and item_id=\"$item_id[0]\" and id=\"$detailid\"");
        } else {
            $result=mysql_query("UPDATE modx_ecomm_cart_detail set (quantity=$qty, date=\"$dat\", options=\"" . $opts['options']. "\", optionsprice=\"" . floatval($opts['price']) . "\") where id=$detailid and item_id=$item_id");
        }
    }

/*
 * This function is used for encoding the options string.  This will return an array containing the options string and the optionsvalue
 * 
 * @param		opts		=	This an array of the names of the options which were selected for an item.
 * @param		item_id		=	This is the ID of the item (NOT THE SKU)
 */
	function encodeoptions($opts, $item_id){
		$price=0;
		$options="";
		
		foreach($opts as $var => $value){
			$option= getoption($item_id, $var);
			$listitem= getlistoption($option['listid']);
			$price= $price + (floatval($listitem['priceoffset']));
			$options= $options + $listitem['name'] + ":" + $value + ";";
		}
		
		$arr['options']=$options;
		$arr['price']=$price;
		return $arr;
	}

/*
 *  This function is used if you want to delete an item without passing me a quantity of zero.  If you're using this you might be considered lazy.
 *  Just pass me your session id and item number and I guess I'll take care of it.
 *
 *  @param 		sessionid     	=	Session ID of the user
 *  @param 		sku        		=   SKU of the item
 *  @param 		detailid		=	This is the id of the detail line to delete
 */
    function deleteitem($sessionid, $itemid){
        $result= mysql_query("SELECT id, datemodified, itemsincart, subtotal from modx_ecomm_cart_header where session_id=\"$sessionid\"") or die ("MY1 ERROR: " . mysql_error());
		$headrec=mysql_fetch_row($result);
		
		$result = mysql_query("SELECT quantity, totalprice from modx_ecomm_cart_detail where header_id=$headrec[0] and id=$itemid") or die ("MY2 ERROR: " . mysql_error());
		$record = mysql_fetch_row($result);
		
		$subtotal= floatval($headrec[3] - $record[1]);
		$itemsincart = floatval($headrec[2] - $record[0]);
		$datemodified = date("D M j G:i:s T Y");
		
		echo "SUB: " . $subtotal . " ITincart: " . $itemsincart . " datemod: " . $datemodified;
        $result=mysql_query("DELETE FROM modx_ecomm_cart_detail where header_id=$headrec[0] and id=$itemid") or die ("MY ERROR: " . mysql_error());
		$result=mysql_query("UPDATE modx_ecomm_cart_header set subtotal=$subtotal, itemsincart=$itemsincart, datemodified=\"$datemodified\" where id=$headrec[0]") or die ("MY4 ERROR: " . mysql_error());
    }

/*
 *  This function is designed as a gateway to process various types of checkouts.
 *  It's only purpose is to redirect to the appropriate handler for the checkout
 *  method chosen during the checkout process.
 */
	function processcheckout($sessionid, $paymethod, $cardtype, $nameoncard, $cardnum, $routenum, $cvvcode, $expmo, $expyr){
		switch ($paymethod){
			// Credit Line offered by Merchant
			case "CREDIT":
				return "MADE IT CREDIT";
			break;
			// Mail a Check
		 	case "CHECK":
				return "MADE IT CHECK";			
			break;
			// Process a credit card with authorize.NET
		 	case "CREDITCARD":
				$headerid=converttoorder($sessionid);
				
				$response=processcc($cc);

			break;
			// Process an eCheck with authorize.NET (not yet implemented)
		 	case "ECHECK":
				return "MADE IT ECHECK";
			break;
			// Add order from a google Checkout (Google takes care of the rest)
		 	case "GOOGLE":	
				return "MADE IT GOOGLE";
			break;
			// Add order from a paypal Checkout (Paypal takes care of the rest)
		 	case "PAYPAL":
				return "MADE IT PAYPAL";
			break;
		}
	}

/*
 *  This function simply converts a cart into an order and sets the appropriate customer id to the order
 * 
 *  @param 		sessionid		=	Session ID of the user attempting to check out
 */
	function converttoorder($sessionid){
		// This is the entire header record from the cart in $hid[0] -> $hid[23]
		$qry  = "SELECT id, itemsincart, subtotal, fname, lname, addr1, addr2, city, state, zip, phone_1, phone_2, ext_1, ext_2, fax, company, ";
		$qry .= "shipfname, shiplname, shipaddr1, shipaddr2, shipcity, shipstate, shipzip, shipphone, shipext, shipcompany from modx_ecomm_cart_header ";
		$qry .= "where session_id=\"$sessionid\"";
		$result=mysql_query($qry) or die ("MYSQL RETRIEVE CART RECORD: " . mysql_error());
        $hedr=mysql_fetch_row($result);

		// $cust[0] is the internalKey of the modx user with the sessionid that was passed in, it should be linked to the customer's orders so
		// that their orders will properly show up in the customer account viewer.  
		$qry = "SELECT internalKey from modx_web_user_attributes where sessionid=\"$sessionid\"";
		$result=mysql_query($qry) or die ("MYSQL RETRIEVE CUST RECORD: " . mysql_error());
		$cust=mysql_fetch_row($result);
		
		// Get Shipping and Handling for order
        $tshp=getship($sessionid);
        $thnd=gethandle($sessionid);
        $rate=0.06;
        $ttax=gettax($sessionid, $rate);
        $totl= gettotal($sessionid, $rate);

		// Generate Date for created entry
        $dat = date("D M j G:i:s T Y");		
		// Copy Cart to an Order
		$qry  = "INSERT INTO modx_ecomm_order_header (";
		$qry .= "cust_id, totshipping, tothandling, tax, total, subtotal, status, orderitems, created, ";
		$qry .= "fname, lname, addr1, addr2, city, state, zip, phone_1, phone_2, ext_1, ext_2, fax, company, ";
		$qry .= "shipfname, shiplname, shipaddr1, shipaddr2, shipcity, shipstate, shipzip, shipphone, shipext, shipcompany) ";
		$qry .= "values (";
		
		// Header / Total Line Info
		$qry .= $cust[0]   . ", ";   		// Cust ID
		$qry .= $tshp      . ", ";          // totshipping
		$qry .= $thnd      . ", ";          // tothandling
		$qry .= $ttax      . ", ";          // tax
		$qry .= $totl      . ", ";          // total
		$qry .= $hedr[2]   . ", ";          // subtotal
		$qry .= "\"NEW\""  . ", "; 			// status
		$qry .= $hedr[1]   . ", "; 		    // orderitems (itemct)
		$qry .= "\"$dat\"" . ", ";          // created (DATETIME)
		
		// Billing Info
		$qry .= "\"" . $hedr[3]  . "\", ";  // fname 
		$qry .= "\"" . $hedr[4]  . "\", ";  // lname
		$qry .= "\"" . $hedr[5]  . "\", ";  // addr1
		$qry .= "\"" . $hedr[6]  . "\", ";  // addr2
		$qry .= "\"" . $hedr[7]  . "\", ";  // city
		$qry .= "\"" . $hedr[8]  . "\", ";  // state
		$qry .= "\"" . $hedr[9]  . "\", ";  // zip
		$qry .= "\"" . $hedr[10] . "\", "; 	// phone_1
		$qry .= "\"" . $hedr[11] . "\", "; 	// phone_2
		$qry .= "\"" . $hedr[12] . "\", "; 	// ext_1
		$qry .= "\"" . $hedr[13] . "\", "; 	// ext_2
		$qry .= "\"" . $hedr[14] . "\", "; 	// fax
		$qry .= "\"" . $hedr[15] . "\", "; 	// company
		
		// Shipping Info
		$qry .= "\"" . $hedr[16] . "\", "; 	// shipfname
		$qry .= "\"" . $hedr[17] . "\", "; 	// shiplname
		$qry .= "\"" . $hedr[18] . "\", "; 	// shipaddr1
		$qry .= "\"" . $hedr[19] . "\", "; 	// shipaddr2
		$qry .= "\"" . $hedr[20] . "\", "; 	// shipcity
		$qry .= "\"" . $hedr[21] . "\", "; 	// shipstate
		$qry .= "\"" . $hedr[22] . "\", "; 	// shipzip
		$qry .= "\"" . $hedr[23] . "\", "; 	// shipphone
		$qry .= "\"" . $hedr[24] . "\", "; 	// shipext
		$qry .= "\"" . $hedr[25] . "\"";   	// shipcompany

		$qry .= ")";
		// Add Header
		$result=mysql_query($qry) or die ("ORDER HEADER ADD ERROR: " . mysql_error());
		
		// Get Header ID
		$qry = "SELECT id from modx_ecomm_order_header where created=\"$dat\" and cust_id=" . $cust[0];
		$result=mysql_query($qry) or die ("ORDER HEADER RETRIEVAL ERROR: " . mysql_error());
		$headid=mysql_fetch_row($result);
		
		//Get Items from the Cart
		$qry = "SELECT item_id, quantity, options, optionsprice, totalprice from modx_ecomm_cart_detail where header_id=" . $hedr[0];
		$result=mysql_query($qry) or die ("GET ITEMS FROM CART ERROR: " . mysql_error());

		// Delete Cart Detail
			$qry = "DELETE from modx_ecomm_cart_detail where header_id=$hedr[0]";
			$res=mysql_query($qry) or die ("MYSQL REMOVE CART DETAIL: " . mysql_error());
		// Delete Cart Header
			$qry = "DELETE from modx_ecomm_cart_header where id=$hedr[0]";
			$res=mysql_query($qry) or die ("MYSQL REMOVE CART DETAIL: " . mysql_error());	

		// Transfer Items into the Order
		for ($i=0; $i < mysql_num_rows($result); $i++){
			$row=mysql_fetch_row($result);
			$qry = "INSERT into modx_ecomm_order_detail (item_id, order_id, quantity, options, optionsprice, totalprice) values ($row[0], $headid[0], $row[1], \"$row[2]\", $row[3], $row[4])";
			$result=mysql_query($qry) or die ("MYSQL: " . mysql_error());
		}
				
		return $headid[0];
	}

/*
 *  This method will create a ModX user account and then it will also create an ecomm customer account
 * 
 *  There are too many parameters to list (and most are obvious)
 * 
 *  The reason that I didn't just create my own login system is because I figure that most modx users
 *  who have an existing website, most likely have existing users.  Thus I don't want to make them 
 *  switch to a new authentication mechanism.  The other nice thing is that the ModX module already
 *  takes care of the login process fairly well, so I didn't see a need to rewrite it.  However, it
 *  only takes in fields which would be associated with posting to a forum or blog...whereas ecommerce
 *  often requires other fields to be stored for customer accounts (ie: an exact address rather than
 *  just a country).  So my module piggy-backs on the existing one.  I first create the modx user
 *  and then I create my modx_ecomm_customers entry to store additional data.
 */

	function createuseraccount($sessionid, $email, $fname, $lname, $addr1, $addr2, $city, $state, $zip, $country, $phone, $ext, $fax, $company, $username, $password){
		// Create fullname
		$fullname=$fname . ' ' . $lname;
		// Create User Account
	    $qry = "INSERT INTO modx_web_users (username, password) VALUES(\"".$username."\", \"".$password."\")";
		$result=mysql_query($qry) or die ("ADD USER ERROR: " . mysql_error());
		
		$qry = "SELECT id from modx_web_users where username=\"$username\" and password=\"$password\"";
		$result=mysql_query($qry) or die ("FIND USER ADDED ERROR: " . mysql_error());
		$row=mysql_fetch_row($result);		
		$id=$row[0];
		
		$qry = "INSERT INTO modx_web_user_attributes (internalKey, fullname, email, zip, state, country)
		       VALUES($id, \"$fullname\", \"$email\", \"$zip\", \"$state\", \"$country\");";
		$result=mysql_query($qry) or die ("INSERT USER ATTRIBUTES ERROR: " . mysql_error());
		
		$qry  = "INSERT INTO modx_ecomm_customers (fname, lname, addr1, addr2, city, state, zip, country, phone_1, ext_1, fax, companyname, custid) ";
		$qry .= "values (";
		$qry .= "'$fname', '$lname', '$addr1', '$addr2', '$city', '$state', '$zip', '$country', '$phone', '$ext', '$fax', '$company', $id)";
		$result=mysql_query($qry) or die ("INSERT CUSTOMER ERROR: " . mysql_error());
		return "DONE: " . $id;
		}

/*
 * This function is called from ModX to process orders.
 *
 * @param   	sessionid   =   This is the session ID of the user so that we can retrieve their cart
 * @param   	cc          =   This is an array of credit card info
 * @param   	cust        =
 */
    function checkout($sessionid, $cc){
        if ($response['approval'] == "APPROVED"){

            $result = mysql_query("INSERT into modx_ecomm_order_header (pay_id, cust_id, totshipping, tothandling, tax, total, subtotal, paymentApproved, authCode, ponumber, status, orderitems) values ($gway, $cust, $tship, $thand, $tax, $total, $hid[1], \"$approval\", \"$authcode\", \"NA\", \"NEW\", $hid[2])") or die ("MYSQL2: " . mysql_error());

            $result = mysql_query("SELECT * from modx_ecomm_order_header where cust_id=$cust and authCode=\"$authcode\"") or die ("MYSQL3: " . mysql_error());
			$ordhdrid = mysql_fetch_row($result);
            
			$result = mysql_query("SELECT item_id, quantity, options, optionsprice, date from modx_ecomm_cart_detail where header_id=$hid[0]") or die ("MYSQL10: " . mysql_error());
			while ($res=mysql_fetch_row($result)){
                 $orditm = mysql_query("INSERT into modx_ecomm_order_detail (item_id, order_id, quantity, options, optionsprice) values ($res[0], $ordhdrid[0], $res[1],\"" .  $res[2] . "\", $res[3])") or die ("MYSQL: " . mysql_error());
            }
            $removedetail = mysql_query("DELETE from modx_ecomm_cart_detail where header_id=$hid[0]");
            $removeheader = mysql_query("DELETE from modx_ecomm_cart_header where session_id=\"$sessionid\"");
            $addauditenty = mysql_query("INSERT into modx_ecomm_audit (order_id, order_status) values ($ordhdrid[0], \"NEW\")") or die ("MYSQL4: " . mysql_error());
        }
    }

/*
 * This function will process a credit card using the appropriate gateway
 * 
 * @param		cc		=	Array of credit card information
 */
    function processcc($cc){
        $resp['approval']="APPROVED";
        $resp['gway']="1";
        //$resp = payment_gateway_authorize();
        $random="";
        for ($i=0; $i < 12; $i++){
            $random .= rand(0,9);
        }
        for ($i=0; $i < 6; $i++){
            $random2 .= rand(0,9);
        }
        $resp['authcode'] = $random;
        $resp['trxnid'] = $random2;
        return $resp;
    }

/*
 * This method's sole purpose is to tell us how many items are in a particular customers cart.
 *
 * @param 		sessionid      =   The customer's session variable so we can find how many items they have in their cart.
 */
    function getitemcount($sessionid) {
        $headerid = mysql_query("SELECT itemsincart from modx_ecomm_cart_header where session_id=\"$sessionid\"");
        $num=mysql_fetch_row($headerid);
        return $num[0];
    }

/*
 * This method is designed to provide the opening form code
 *
 * @param 		itemid		=   ID to generate a form header for
 * @param		action		=   Location of script to run on submit (POST)
 */
    function openform_plain($itemid, $name, $act){
        $open  = '<form name="' . $name . '" id="' . $name . '" method="POST" action="' . $act . '">' . "\n";
        return $open;
    }

/*
 * Gets the fullname stored in the database of the item
 * 
 * @param		itemid		=	ID of the item to retrieve a full name
 */
    function getfullname($itemid){
        $res = mysql_query("SELECT fullname from modx_ecomm_items where id=$itemid") or die ("MYSQL ERROR: " . mysql_error());
        $fullname=mysql_fetch_row($res);
        return $fullname[0];
    }

/*
 * Gets the description stored in the database of the item
 * 
 * @param 		itemid		=	ID of the item to retrieve a description
 */
    function getdescription($itemid){
        $res = mysql_query("SELECT description from modx_ecomm_items where id=$itemid") or die ("MYSQL ERROR: " . mysql_error());
        $description=mysql_fetch_row($res);
        return $description[0];
    }

/*
 * Gets the name stored in the database of the item
 * 
 * @param		name		=	ID of the item to retrieve a name
 */
    function getname($itemid){
        $res = mysql_query("SELECT name from modx_ecomm_items where id=$itemid") or die ("MYSQL ERROR: " . mysql_error());
        $name=mysql_fetch_row($res);
        return $name[0];
    }

/*
 * This method is designed to retrieve the item price from the database and return it to be displayed.
 *
 * @param		itemid			=	ID of the item whose price you wish to display
 */
    function getprice($itemid){
        $price= mysql_query("select amount from modx_ecomm_items where id=$itemid");
        $price=mysql_fetch_row($price);
        return number_format($price[0], 2);
    }
/*
 * This is designed to return the subtotal
 * 
 * @param		sessionid		=	Session ID of the user
 */
    function getsubtotal($sessionid){
        $subtot = mysql_query("SELECT subtotal from modx_ecomm_cart_header where session_id=\"$sessionid\"") or die ("MYSQL ERROR: " . mysql_error());
        $sub=mysql_fetch_row($subtot);
		$s = floatval($sub[0]);
        return number_format($s, 2);
    }

/*
 * This is designed to return the grand total for a given subtotal and tax
 * 
 * @param 		subt		=	Subtotal of the order
 * @param		tax			=	Tax on the order
 * @param		ship		=	Shipping on the order
 * @param		hnd			=	Handling on the order
 */
    function gettotal($sessionid, $rt){
        $subtot = mysql_query("SELECT subtotal from modx_ecomm_cart_header where session_id=\"$sessionid\"") or die ("MYSQL ERROR: " . mysql_error());
        $sub=mysql_fetch_row($subtot);
		$s = floatval($sub[0]);
        $t=gettax($sessionid, $rt);
		$sh=getship($sessionid);
		$h=gethandle($sessionid);
        return $s + $t + $sh +$h;
    }

/*
 * This is designed to return the shipping cost for a given set of items
 * 
 * @param $sessionid		=	Session ID of the user attempting to check out
 */
	function getship($sessionid){
		$shipcost=5.00;
		return number_format($shipcost,2);	
	}

/*
 * This is designed to return the handling cost for a given set of items
 * 
 * @param sessionid		=	Session ID of the user attempting to check out
 */
	function gethandle($sessionid){
		$handlecost=5.00;
		return number_format($handlecost,2);
	}

/*
 * Gets tax using just a user's sessionid
 * 
 * @param 		sessionid		=	Session ID of the user
 * @param		rt				=	Tax Rate to apply
 */
    function gettax($sessionid, $rt){
        $subtot = mysql_query("SELECT subtotal from modx_ecomm_cart_header where session_id=\"$sessionid\"") or die ("MYSQL ERROR: " . mysql_error());
        $sub=mysql_fetch_row($subtot);
        $s=floatval($sub[0]);
        $t=floatval($rt);
        $tot= ($s*$t);
        return number_format($tot,2);
    }

/*
 * This method is designed to provide the opening form code
 */
    function closeform_plain(){
        $button = "<input type=\"image\" src=\"http://images.paypal.com/en_US/i/btn/x-click-but22.gif\" border=\"0\" name=\"submit\" width=\"87\" height=\"23\" alt=\"Add to Cart!\">";
        $button .= "</form>";
        return $button;
    }

/*
 * This method will make a javascript form header
 * 
 * @param 	id		=	ID of the form header to add
 */
	function openadditemform_js($id){
		$formhdr  = "<form id=\"$id\" method=\"POST\" action=\"javascript: get(document.getElementById('$id'))\">";
		return $formhdr;
	}

/*
 * This method will make a javascript addtocart button at the bottom of the page
 * 
 * @return 	The code to output a javascript based submit button an item page
 */
	function closeadditemform_js(){
		$button  = 'input type="hidden" id="item_id" name="item_id" value="[*ProductNumber*]" />' . "\n";
		$button .= '<input type="hidden" id="sessionid" name="sessionid" value="' . session_id() . '">' . "\n";
	    $button .= '<input type="image" src="http://images.paypal.com/en_US/i/btn/x-click-but22.gif" border="0" name="submit" onclick="additemtocart();" width="87" height="23" alt="Add to Cart!">' . "\n";
        $button .= '</form>';
		
        return $button;
	}

/*
 * This method is designed to provide a checkout button.
 */
    function closeform_checkout(){
        $button =  "<input class=\"itema_checkoutbutton\" type=\"submit\" value=\"Proceed to Checkout\" name=\"proceedtocheck\" onClick=\"checklogin();\" alt=\"Proceed to Login / Address \">";
        return $button;
    }

/*
 * This method is designed to provide a return to shopping button (after you add an item to your cart)
 */
    function closeform_returnbutton(){
        $button  = "<input class=\"itema_checkoutbutton\" type=\"submit\" value=\"Continue Shopping\" name=\"returntoshop\" alt=\"Return to Shopping\">";
        return $button;
    }

/*
 * This function will make the button required to validate the shipping / billing info
 */
    function closeform_verifycheckout(){
        $button =  "<input class=\"itema_checkoutbutton\" type=\"submit\" value=\"Verify\" name=\"proceedtocheck\" onClick=\"checkshipandbill();\" alt=\"Verify for Checkout\">";
        return $button;
    }

/*
 * This function will make the button required to create an ecommerce account
 */
    function closeform_signupform(){
        $button =  "<input class=\"itema_checkoutbutton\" type=\"submit\" value=\"Signup\" name=\"signupbutton\" onMouseOver=\"checkusername();checkemail();\" onClick=\"checksignup();\" alt=\"Signup\">";
        return $button;
    }

/*
 * This method will make the button required to process the final checkout screen
 */
    function closeform_processcheckout(){
       $button  = '<input class="itema_checkoutbutton" type="submit" value="Process Checkout" name="processcheckout" alt="Process Checkout">';
       return $button;

    }

/*
 * This will add the item to the ModX content page database
 *
 * @param 		pagetitle     =   Title of the page
 * @param 		longtitle     =   Long title of the page
 * @param 		description   =   Description of the page
 * @param 		published     =   Boolean 1 Published / 0 Not
 * @param 		parent        =   Integer FK relationship to parent document 49 for us
 * @param 		richtext      =   Boolean 1 RT Editor / 0 Plain
 * @param 		template      =   Integer FK relationship to template 7 for product template
 * @param 		searchable    =   Boolean 1 Searchable / 0 Not
 * @param 		cacheable     =   Boolean 1 Cacheable / 0 Not
 * @param 		menutitle     =   Title to show in the menu
 * 
 * NOTE: 5  is the template variable id for [*ProductNumber*]
 * 		 7  is the template ID of the product template
 * 		 49 is the parent document id
 */
    function addcontainer($item_id, $sku, $content, $pagetitle, $longtitle, $description, $published, $parent, $richtext, $template, $searchable, $cacheable, $menutitle){
        $cont = $content;
        $timeraw=time();
        $qry  =  "INSERT into modx_site_content (type, contentType, pagetitle, longtitle, description, published, parent, richtext, template, searchable, cacheable, createdby, createdon, content, menutitle)";
        $qry .= "values (";
        $qry .= "\"document\", \"text/html\", \"$pagetitle\", \"$longtitle\", \"$description\", $published, $parent, $richtext, $template, $searchable, $cacheable, 1, $timeraw, \"$cont\", \"$menutitle\"";
        $qry .= ")";

        $res = mysql_query($qry) or die ("MYSQL: " . mysql_error());

        $qry = "SELECT id from modx_site_content where pagetitle=\"$pagetitle\" AND longtitle=\"$longtitle\" and createdon=$timeraw";
        $res = mysql_query($qry) or die ("MYSQL: " . mysql_error());
        $row = mysql_fetch_row($res);
        $contentid=intval($row[0]);

        $qry = "INSERT INTO modx_site_tmplvar_contentvalues (tmplvarid, contentid, value) values (4508, $contentid, \"$sku\")";
        $res = mysql_query($qry) or die ("MYSQL: " . mysql_error());
		return $contentid;
    }

/*
 * Used to Write an Item to the database.  This might be utilized by external applications to produce a record
 * in the catalog (or update / delete) an existing record
 *
 *  @param 		num       			=   Item Number
 *  @param 		name      			=   Item Name  
 *  @param 		amt       			=   Item Cost  
 *  @param 		hazmat    			=   Hazardous Materials Add'l Shipping Cost
 *  @param 		oversized 			=   Oversized Item Shipping Cost
 *  @param		shoppingenabled 	=	BOOL 1=SHOP ENABLED 0=SHOP DISABLED
 *  @param 		quoteenabled		=	BOOL 1=QUOTE ENABLED 0=QUOTE DISABLED
 *  @param		disabled			= 	OPP OF THE VAR I TAKE IN THE PARENT METHOD...$active=0 --> $disabled=1
 *  @param 		type      			=   Trans Type            
 */
    function writeitemtodb($num, $name, $shortdescription, $amt, $hazmat, $oversized, $shoppingenabled, $quoteenabled, $disabled, $type) {
		$audqry="";
        if ($type == "NEW"){
            $qry  = "INSERT INTO modx_ecomm_items (name, amount, hazmat, oversized, shoppingenabled, quoteenabled, disabled) ";
            $qry .= "values (\"$name\", $amt, $hazmat, $oversized, $shoppingenabled, $quoteenabled, $disabled)";
        } else if ($type == "UPDATED"){
			$qry  = "SELECT items_id from modx_ecomm_items_audit where id=$num";
			$result=mysql_query($qry);
			$row=mysql_fetch_row($result);
			$numid=$row[0];
            $qry  = "Update modx_ecomm_items set name=\"$name\", ";
            $qry .= "amount=$amt, ";
			$qry .= "description=\"$shortdescription\", ";
            $qry .= "hazmat=$hazmat, ";
            $qry .= "oversized=$oversized, ";
			$qry .= "shoppingenabled=$shoppingenabled, ";
			$qry .= "quoteenabled=$quoteenabled, ";
			$qry .= "disabled=$disabled ";
            $qry .= "where id=$numid";
		} else if ($type == "DELETE"){
            $qry = "Update modx_ecomm_items set disable=1 where id=$num";
        }
		
		$result=mysql_query($qry) or die ("MYSQL ADD ITEM TO DB ERROR: " . mysql_error());
		
		if ($type=="NEW"){
			$qry  = "SELECT id from modx_ecomm_items where name=\"$name\"";
//			$qry .= " AND shoppingenabled=$shoppingenabled AND quoteenabled=$quoteenabled AND disabled=$disabled AND hazmat=$hazmat AND oversized=$oversized";
			$result=mysql_query($qry) or die ("MYSQL FIND NEW ITEM ERROR: " . mysql_error());
			$row=mysql_fetch_row($result);
			$itemid=$row[0];
			$audqry  = "INSERT INTO modx_ecomm_items_audit (items_id, sku, name, description, amount, hazmat, oversized, disabled, shoppingenabled, quoteenabled, status) values ";
			$audqry .= "($itemid, $itemid, \"$name\", \"$shortdescription\", $amt, $hazmat, $oversized, $disabled, $shoppingenabled, $quoteenabled, \"NEW\")";
			$result=mysql_query($audqry) or die ("MYSQL COULD NOT ADD AUDIT ENTRY: " . mysql_error());
		} else if ($type=="UPDATED"){
			$qry  = "SELECT id from modx_ecomm_items where name=\"$name\"";
//			$qry .= " AND shoppingenabled=$shoppingenabled AND quoteenabled=$quoteenabled AND disabled=$disabled AND hazmat=$hazmat AND oversized=$oversized";
			$result=mysql_query($qry) or die ("MYSQL FIND NEW ITEM ERROR: " . mysql_error());
			$row=mysql_fetch_row($result);
			$itemid=$row[0];
			$audqry  = "UPDATE modx_ecomm_items_audit set ";
			$audqry .= "name=\"$name\", description=\"$shortdescription\", amount=$amt, hazmat=$hazmat, oversized=$oversized, disabled=$disabled, shoppingenabled=$shoppingenabled, quoteenabled=$quoteenabled, status=\"UPDATED\" where id=$num";
			$result=mysql_query($audqry) or die ("MYSQL COULD NOT ADD AUDIT ENTRY: " . mysql_error());				
		}
		
        return $itemid;
    }

/*
 * This function implements the Authorize.NET payment gateway
 * 
 * @param		custarr		=	Array of customer information
 * @param		cc			=	Array of credit card information
 * @param		amount		=	amount to charge to user's credit card
 * 
 * NOTE: When j is greater than 69, these fields are custom and defined
 *       by the merchant
 */
    function payment_gateway_authorize($custarr, $cc, $amount){
        $DEBUGGING                  = 1;               
        $TESTING                    = 1;               
        $ERROR_RETRIES              = 2;         

        $auth_net_login_id          = "6g8H579MfDx";
        $auth_net_tran_key          = "6xZCE6F3h6gJZ326";
        $auth_net_url               = "https://test.authorize.net/gateway/transact.dll";
        $authnet_values             = array
        (
               "x_login"               => $auth_net_login_id,
               "x_version"             => "3.1",
               "x_delim_char"          => "|",
               "x_delim_data"          => "TRUE",
               "x_url"                 => "FALSE",
               "x_type"                => "AUTH_CAPTURE",
               "x_method"              => "CC",
               "x_tran_key"            => $auth_net_tran_key,
               "x_relay_response"      => "FALSE",
               "x_card_num"            => "4242424242424242",
               "x_exp_date"            => "1209",
               "x_description"         => "Recycled Toner Cartridges",
               "x_amount"              => "12.23",
               "x_first_name"          => "Charles D.",
               "x_last_name"           => "Gaulle",
               "x_address"             => "342 N. Main Street #150",
               "x_city"                => "Ft. Worth",
               "x_state"               => "TX",
               "x_zip"                 => "12345",
               "CustomerBirthMonth"    => "Customer Birth Month: 12",
               "CustomerBirthDay"      => "Customer Birth Day: 1",
               "CustomerBirthYear"     => "Customer Birth Year: 1959",
               "SpecialCode"           => "Promotion: Spring Sale",
           );

        $fields = "";
        foreach( $authnet_values as $key => $value ) $fields .= "$key=" . urlencode( $value ) . "&";
            $ch = curl_init("https://test.authorize.net/gateway/transact.dll");
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim( $fields, "& " )); 
            //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            $resp = curl_exec($ch);
            curl_close ($ch);
            $text = $resp;
            $h = substr_count($text, "|");
            $h++;
            $returnresp['gway']=1;
            $returnresp['approval']="APPROVED";
            for($j=1; $j <= $h; $j++){

               $p = strpos($text, "|");

               if ($p === false) { 
                    if($j>=69){
                    }else{
                    }
                } else {
                    $p++;
                    $pstr = substr($text, 0 , $p);

                    $pstr_trimmed = substr($pstr, 0, -1);

                    if($pstr_trimmed==""){
                        $pstr_trimmed="NO VALUE RETURNED";
                    }

                    switch($j){
                        case 1:
                            if($pstr_trimmed=="1"){
                                $returnresp['approval']="APPROVED";
                            }elseif($pstr_trimmed=="2"){
                                $returnresp['approval']="DECLINED";
                            }elseif($pstr_trimmed=="3"){
                                $returnresp['approval']="ERROR";
                            }
                        break;

                        case 5:
                            $returnresp['authcode']=$pstr_trimmed;
                            echo "<br />AUTHCODE: " . $returnresp['authcode'] . "<br />";
                        break;

                        case 7:
                            $returnresp['trxnid']=$pstr_trimmed;
                        break;

                        default:

                            if($j>=69){
                            }
                            else{
                            }
                        break;
                    }
                }
            }
        return $returnresp;
    }

/*
 *  This function is designed to create the hidden fields required for a POST back google checkout.  When a person
 *  chooses google at checkout it will generate a button with the appropriate merchant ID, tax rate, etc.
 * 
 * @param		sessionid		=	Session ID of the user
 * 
 * Note...to implement this correctly, you need to have a web service with 128bit TLS encryption running to receive
 * a notification callback from Google.  This is basically an XML parser that listens for the response, most likely
 * SOAP.  I will implement one for ITema when we have a certificate to sign our server with, but for now, you'll have
 * to go ensure that the payment was processed.
 * 
 */
	function googlecheckout($sessionid){		
		$merchantid = "815885240347814";
		$webserver = "sandbox.google.com";
		$shipmethod = "UPS Ground";
		$shipprice = getship($sessionid) + gethandle($sessionid);
		$taxrt = "0.06";
		$taxstate = "CT";
		
		echo "<form method=\"POST\" action=\"https://". $webserver. "/checkout/cws/v2/Merchant/" . $merchantid . "/checkoutForm\" accept-charset=\"utf-8\">\n";
	            
		// Go grab the items from the users cart
				
		$qry = "SELECT id, fname, lname, addr1, addr2, city, state, zip, cust_id from modx_ecomm_cart_header where session_id=\"$sessionid\"";
		$result=mysql_query($qry) or die ("MYSQL GET HEADER: " . mysql_error());
		$hdr = mysql_fetch_row($result);
			
		$qry  = "SELECT A.id, A.name, A.description, quantity, options, optionsprice, totalprice from modx_ecomm_cart_detail as B";
		$qry .= "INNER JOIN modx_ecomm_items as A ON item_id = A.id where header_id=" . $hdr[0];
		
		$result=mysql_query($qry) or die ("MYSQL GET CART ITEMS: " . mysql_error());
		
		for ($i=0; $i < mysql_num_rows($result); $i++){
			$row = mysql_fetch_row($result);
			$k = $i + 1;
			echo "<input type=\"hidden\" name=\"item_name_$k\" value=\"" . $row[1] . "\"/>\n";
	   	 	echo "<input type=\"hidden\" name=\"item_description_$k\" value=\"" . $row[2] . "<br />Options: " . $row[4] . "<br />Options Price: " . $row[5] . "\"/>\n";
			echo "<input type=\"hidden\" name=\"item_quantity_$k\" value=\"" . $row[3] . "\"/>\n";
       		echo "<input type=\"hidden\" name=\"item_price_$k\" value=\"" . ($row[6]/$row[3]) . "\"/>\n";
		}
		  
		echo "<input type=\"hidden\" name=\"ship_method_name_1\" value=\"" . $shipmethod . "\"/>\n";
		echo "<input type=\"hidden\" name=\"ship_method_price_1\" value=\"" . $shipprice . "\"/>\n";
		  
		echo "<input type=\"hidden\" name=\"tax_rate\" value=\"0.06\"/>\n";
		echo "<input type=\"hidden\" name=\"tax_us_state\" value=\"" . $taxstate . "\"/>\n";
			  
		echo "<input type=\"hidden\" name=\"_charset_\" />\n";
		echo "<input type=\"image\" name=\"Google Checkout\" alt=\"Fast checkout through Google\" src=\"http://" . $webserver . "/checkout/buttons/checkout.gif?merchant_id=" . $merchantid . "&w=180&h=46&style=trans&variant=text&loc=en_US\" height=\"46\" width=\"180\"/>\n";
		echo "</form>";	
	}

/*
 *  This function is designed to create the hidden fields required for a POST back paypal checkout.  When a person chooses
 *  to check out via paypal, this will auto-generate the button and fields which are required to send to PayPals website.
 * 
 *  @param 		sessionid		=	Session ID of the user
 * 
 *  Note...like google, some research should be done into how this works fully implemented...is it secure?  Do we need to send
 *  from a TLS encrypted site (obviously).  
 */
	function paypalcheckout($sessionid){
		$merchantid = "cjbur2@conncoll.edu";
		$webserver = "www.paypal.com";
		$shipmethod = "UPS Ground";
		$shipprice = getship($sessionid);
		$handleprice = gethandle($sessionid);
		$snh = $shipprice + $handleprice;
		$taxrt = .06;
		$tax = gettax($sessionid, $taxrt);
		$ctry = "US";
		
		echo "<form method=\"POST\" action=\"https://". $webserver. "/cgi-bin/webscr/\">";

		echo "<input type=\"hidden\" name=\"cmd\" value=\"_cart\">";
		echo "<input type=\"hidden\" name=\"upload\" value=\"1\">";
	    echo "<input type=\"hidden\" name=\"business\" value=\"". $merchantid . "\">";        
		// Go grab the items from the users cart
				
		$qry = "SELECT id, fname, lname, addr1, addr2, city, state, zip, cust_id from modx_ecomm_cart_header where session_id=\"$sessionid\"";
		$result=mysql_query($qry) or die ("MYSQL GET HEADER: " . mysql_error());
		$hdr = mysql_fetch_row($result);
		$qry = "SELECT email from modx_web_user_attributes where sessionid=\"$sessionid\"";
		$result=mysql_query($qry);
		$modxcust=mysql_fetch_row($result);
			
		$qry  = "SELECT A.id, A.name, A.description, quantity, options, optionsprice, totalprice from modx_ecomm_cart_detail as B";
		$qry .= "INNER JOIN modx_ecomm_items as A ON item_id = A.id where header_id=" . $hdr[0];
		
		$result=mysql_query($qry) or die ("MYSQL GET CART ITEMS: " . mysql_error());
		
		for ($i=0; $i < mysql_num_rows($result); $i++){
			$row = mysql_fetch_row($result);
			$k = $i + 1;
			echo "<input type=\"hidden\" name=\"item_name_$k\" value=\"" . $row[1] . "\">";
			echo "<input type=\"hidden\" name=\"quantity_$k\" value=\"" . $row[3] . "\">";
       		echo "<input type=\"hidden\" name=\"amount_$k\" value=\"" . ($row[6] / $row[3]) . "\">";
		}		
		echo "<input type=\"hidden\" name=\"tax_cart\" value=\"$tax\">";
		echo "<input type=\"hidden\" name=\"handling_cart\" value=\"$snh\" />";
		echo "<input type=\"hidden\" name=\"first_name\" value=\"" . $hdr[1] . "\" />";
		echo "<input type=\"hidden\" name=\"last_name\" value=\"" . $hdr[2] . "\" />";
		echo "<input type=\"hidden\" name=\"address1\" value=\"" . $hdr[3] . "\" />";
		echo "<input type=\"hidden\" name=\"address2\" value=\"" . $hdr[4] . "\" />";
		echo "<input type=\"hidden\" name=\"city\" value=\"" . $hdr[5]. "\" />";
		echo "<input type=\"hidden\" name=\"state\" value=\"" . $hdr[6] . "\" />";
		echo "<input type=\"hidden\" name=\"zip\" value=\"" . $hdr[7] . "\" />";
		echo "<input type=\"hidden\" name=\"email\" value=\"" . $modxcust[0] . "\" />";
		echo "<input type=\"image\" name=\"Paypal Checkout\" alt=\"Fast checkout through Paypal\" src=\"assets/snippets/shoppingCart/paypal_button.gif\">";
		echo "</form>";	
			
	}

/*
 * This function will create a new option for a particular item.
 * It will also create a CHUNK in modx, that way the option can
 * easily be displayed on the item page or added to a template
 *
 * PREREQ:  The item record must exist and the list for the item's
 *          options should already be created before calling this
 *          method.
 *
 * @param 		listid    	=   ID of the list which will provide options for
 *              		        the item.
 * @param 		name      	=   Name of the option
 * @param 		renderas 	=   How to render the option (CHECK, TEXT, TEXTAREA,
 *                      	    RADIO, MULTI, SELECT)
 * @param 		htmlclass	=	CSS class for the option
 * @param		size 		=	Size of the field (also used for num of rows for textarea)
 * @param		length		=	Mostly used for storing the number of columns
 * @param		deflt		=	Default option id or text to display
 */
    function createoption($listid, $name, $renderas, $htmlclass, $size, $length, $deflt){
		$itemid=0;
		if ($renderas=="DROP"){
			$renderas="SELECT";	
		}
		
        $qry  = "INSERT into modx_ecomm_options (";
        $qry .= "item_id, lists_id, name, renderas, htmlclass, size, length, deflt";
        $qry .= ") values (";
        $qry .= "$itemid, $listid, \"$name\", \"$renderas\", \"$htmlclass\"," . floatval($size) . "," . floatval($length) . ",\"$deflt\"";
        $qry .= ")";

        $result=mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
		
        $edit_type=0;
        $category=20;
        $cache_type=0;
        $locked=0;

        $result = mysql_query("SELECT id from modx_site_htmlsnippets where name=\"$name\"");
        if (mysql_num_rows($result) == 0 ){
            //echo "NO RESULTS RETURNED, ADDING HTML CHUNK";

            $snippet = "[[ecomm? &elem=OPTIONS&optionname=" . $name . "]]";
            $qry  = "INSERT into modx_site_htmlsnippets (";
            $qry .= "name, editor_type, category, cache_type, snippet, locked";
            $qry .= ") values (";
            $qry .= "\"$name\", $edit_type, $category, $cache_type, \"$snippet\", $locked";
            $qry .= ")";
 			$result=mysql_query($qry) or die ("INSERT TO CHUNK FAILED: " . mysql_error());
        }
    }

/*
 * This function will update an exisiting option record
 * 
 *   PREREQ: The lists of options should already be created before calling this
 *           method.
 * 
 * @param		optionid	=	ID of the option to render
 * @param 		listid   	=   ID of the list which will provide options for
 *              		        the item.
 * @param 		name      	=   Name of the option
 * @param 		renderas  	=   How to render the option (CHECK, TEXT, TEXTAREA,
 *                      	    RADIO, MULTI, SELECT)
 * @param 		htmlclass	=	CSS class for the option
 * @param		size 		=	Size of the field (also used for num of rows for textarea)
 * @param		length		=	Mostly used for storing the number of columns
 * @param		deflt		=	Default option id or text to display
 */
    function updateoption($optionid, $listid, $name, $renderas, $htmlclass, $size, $length, $deflt){
		if ($renderas=="DROP"){
			$renderas="SELECT";	
		}
		
        $qry  = "UPDATE modx_ecomm_options set ";
        $qry .= "lists_id=$listid, name=\"$name\", renderas=\"$renderas\", htmlclass=\"$htmlclass\", size=" . floatval($size) . ", length=" . floatval($length). ", deflt=\"$deflt\"";
        $qry .= "where id=$optionid";

        $result=mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
		
        $edit_type=0;
        $category=20;
        $cache_type=0;
        $locked=0;

        //$result = mysql_query("SELECT id from modx_site_htmlsnippets where name=\"$name\"");
        //if (mysql_num_rows($result) == 0 ){
            //echo "NO RESULTS RETURNED, ADDING HTML CHUNK";

        //   $snippet = "[[ecomm? &elem=OPTIONS&OPTION_NAME=" . $name . "]]";

        //    $qry  = "INSERT into modx_site_htmlsnippets (";
        //    $qry .= "name, editor_type, category, cache_type, snippet, locked";
        //    $qry .= ") values (";
        //    $qry .= "\"$name\", $edit_type, $category, $cache_type, \"$snippet\", $locked";
        //    $qry .= ")";
            //$result=mysql_query($qry);
        //}
    }

/*
 * This function is designed to delete an option from the database
 * 
 * @param		id		=	ID of the option to delete
 */
	function deleteoption($id){
		$qry  = "DELETE FROM modx_ecomm_options where id=$id";
		$result = mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
		
		//TODO CHANGE SNIPPET TO RETURN NOTHING (BLANK CONTENT)
	}

/*
 * This will create a new header for a blank list.  The list is populated
 * by adding rows in the modx_ecomm_lists_options table with FK relations.
 *
 * @param   	name            =   Name of the list
 * @param   	description     =   Description of the list
 */
    function createlist($name, $description){
        $qry  = "INSERT into modx_ecomm_lists (";
        $qry .= "name, description";
        $qry .= ") values (";
        $qry .= "\"$name\", \"$description\"";
        $qry .= ")";

        $result=mysql_query($qry) or die("CREATELISTFAILED: " . mysql_error());

        $qry = "SELECT id from modx_ecomm_lists where name=\"$name\"";
        $result=mysql_query($qry);
        $row = mysql_fetch_row($result);
        return (intval($row[0]));
    }

/*
 * This method is designed to update the properties of a list
 * 
 * @param	id			=	ID of the list from mySQL
 * @param	name		=	Updated name of the list
 * @param 	description	=	Updated description of the list
 */
	function updatelist($id, $name, $description){
		$qry  = "UPDATE modx_ecomm_lists ";
		$qry .= "set name=\"$name\", description=\"$description\" ";
		$qry .= "where id=$id";
		
		$result=mysql_query($qry) or die ("UPDATE LIST FAILED: " . mysql_error());
	}

/*
 * This function is designed to update a list option
 * 
 * @param 	id			=	ID of the list option
 * @param	name		=	Name of the list option
 * @param	value		=	Value of the list option
 * @param	offset		=	Price Offset of the list option
 */
	function updatelistoption($id, $name, $value, $offset){
		$offsetfloat=floatval($offset);
		$qry  = "UPDATE modx_ecomm_lists_options ";
		$qry .= "set name=\"$name\", value=\"$value\", priceoffset=$offsetfloat ";
		$qry .= "where id=$id";
		
		$result=mysql_query($qry) or die ("UPDATE LIST ITEM FAILED: " . mysql_error());
	}


/*
 * This will delete a list when passed the id
 */
	function deleteList($id){
		$qry = "DELETE from modx_ecomm_lists_options where lists_id=$id";
		$result=mysql_query($qry);
		
		$qry = "DELETE from modx_ecomm_lists where id=$id";
		$result=mysql_query($qry);
	}

/*
 * This will get the PK ID's of all options that are to be displayed for a
 * particular item.  This will return an associative indexed array.
 *
 * @param   	itemid  =   This is the itemid of the item for which we want to
 *              	        obtain options.
 */
    function getalloptions($itemid){
        $qry  = "SELECT lists_id, name, renderas, htmlclass, size, length, default ";
        $qry .= "from modx_ecomm_options ";
        $qry .= "where item_id=$itemid";

        $result=mysql_query($qry);
        $opts="";
        $i=0;
        while ($row=mysql_fetch_row($result)){
            $opts['lists_id'][$i]=$row[0];
            $opts['name'][$i]=$row[1];
            $opts['renderas'][$i]=$row[2];
            $opts['htmlclass'][$i]=$row[3];
            $opts['size'][$i]=$row[4];
            $opts['length'][$i]=$row[5];
            $opts['default'][$i]=$row[6];
            $i++;
        }

        return $opts;

    }


//TODO: FIGURE OUT WHERE THIS METHOD IS USED IF AT ALL!!!

/*
 * This will return an option with a particular
 *
 * @param   	name    =   The name of the option to retrieve
 */
    function getoption($item_id){
        $qry  = "SELECT lists_id, name, renderas, htmlclass, size, length, deflt ";
        $qry .= "from modx_ecomm_options ";
        $qry .= "where id=$item_id";
        $result=mysql_query($qry);
        $row=mysql_fetch_row($result);
        $opts['listid']=$row[0];
        $opts['name']=$row[1];
        $opts['renderas']=$row[2];
        $opts['htmlclass']=$row[3];
        $opts['size']=$row[4];
        $opts['length']=$row[5];
        $opts['default']=$row[6];
        return $opts;
    }

/*
 * This will return the an option with a particular name
 *
 * @param   	name    =   The name of the option to retrieve
 */
    function getoptionbyname($name){
        $qry  = "SELECT lists_id, renderas, htmlclass, size, length, deflt ";
        $qry .= "from modx_ecomm_options ";
        $qry .= "where name=\"$name\"";
        $result=mysql_query($qry) or die ("Could not get OPTIONINFO: " . mysql_error());
        $row=mysql_fetch_row($result);
        $opts['listid']=$row[0];
        $opts['renderas']=$row[1];
        $opts['htmlclass']=$row[2];
        $opts['size']=$row[3];
        $opts['length']=$row[4];
        $opts['default']=$row[5];
        return $opts;
    }

/*
 * This method is for the admin interface.  It is only designed to return the
 * names of all lists.  It will return an associative indexed array.
 */
    function getalllists(){
        $qry = "SELECT id, name, description from modx_ecomm_lists";

        $result=mysql_query($qry) or die ("CAN'T RETRIEVE LISTS: " . mysql_error());;
        $lists="";
        $i=0;
        while ($row=mysql_fetch_row($result)){
            $lists['id'][$i]=$row[0];
            $lists['name'][$i]=$row[1];
            $lists['description']=$row[2];
            $i++;
        }
        return $lists;
    }

/*
 * This is designed to return the name and description of a list.
 * 
 * @param 	listid		=	The id of the list to return values for
 */
	function getlistproperties($listid){
		$qry = "SELECT name, description from modx_ecomm_lists where id=$listid";
		$result=mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
		$listproperties="";
		$row=mysql_fetch_row($result);
		$listproperties['name']=$row[0];
		$listproperties['description']=$row[1];
		return $listproperties;
	}

/*
 * This is designed to return the name, description and price offset of a list option.
 * 
 * @param 	listoptionid		=	The ID of the list option to return
 */
	function getlistoptionproperties($listoptionid){
		$qry = "SELECT name, value, priceoffset from modx_ecomm_lists_options where id=$listoptionid";
		$result=mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
		if ($result){
			$row=mysql_fetch_row($result);
			$opt['name']=$row[0];
			$opt['value']=$row[1];
			$opt['offset']=$row[2];
		}
		return $opt;
	}

/*
 * This method will get all list options in a particular list
 *
 * @param   listid  =   This is the id of the list for which we want options
 */
    function getlistoptions($listid){
        $qry = "SELECT id, name, value, priceoffset from modx_ecomm_lists_options where lists_id=$listid";
        $result=mysql_query($qry) or die ("CANT GET OPTIONS: " . " LISTID: " . $listid . " " . mysql_error());
        $opts="";
        $i=0;
        while ($row=mysql_fetch_row($result)){
			$opts['id'][$i]=$row[0];
            $opts['name'][$i]=$row[1];
            $opts['value'][$i]=$row[2];
            $opts['priceoffset'][$i]=$row[3];
            $i++;
        }
        return $opts;
    }

/*
 * This method will get all list options in a particular list by the name of the list
 * 
 * @param 	name	=	This is the name of the list
 */
	function getlistoptionsbyname($name){
		$qry = "SELECT id from modx_ecomm_lists where name=\"$name\"";
		$result=mysql_query($qry) or die ("TROUBLE GETTING LIST ID: " . mysql_error());
		$row=mysql_fetch_row($result);
		
		$qry = "SELECT id, name, value, priceoffset from modx_ecomm_lists_options where lists_id=" . $row[0];
		$result=mysql_query($qry) or die ("TROUBLE OBTAINING OPTIONS: " . mysql_error());
		$opts="";
		$i=0;
		while ($row=mysql_fetch_row($result)){
			$opts['id'][$i]=$row[0];
			$opts['name'][$i]=$row[1];
			$opts['value'][$i]=$row[2];
			$opts['priceoffset'][$i]=$row[3];
			$i++;
		}
		return $opts;
	}

/*
 * This method will retrieve the details of a list option by using its id
 * 
 * @param		id		=	ID of the list item to return
 */
	function getlistoption($id){
		$qry = "SELECT name, value, priceoffset from modx_ecomm_lists_options where id=$id";
		$result=mysql_query($qry);
		$row=mysql_fetch_row($result);
		
		$opts="";
		$opts['name']=$row[0];
		$opts['value']=$row[1];
		$opts['priceoffset']=$row[2];
		
		return $opts;
	}

/*
 * This method is designed to add an option in the appropriate table for a given
 * list
 *
 * @param   	listid  =   ID of the list to associate with this option
 * @param   	name    =   Name of the option to add
 * @param   	value   =   Value of the option to add
 * @param   	offset  =   Offset of the option to add
 */
    function createlistoption($listid, $name, $value, $offset){
		$off=floatval($offset);
        $qry  = "INSERT into modx_ecomm_lists_options (";
        $qry .= "lists_id, name, value, priceoffset";
        $qry .= ") values (";
        $qry .= "$listid, \"$name\", \"$value\", \"$off\"";
        $qry .= ")";
        $result=mysql_query($qry) or die("MYSQL ERROR: " . mysql_error());
    }

/*
 * This method is desiged to delete an option from a specified list
 * 
 * @param		id		=	ID number of the row to delete
 */
	function deletelistoption($listoptionid){
		$qry  = "DELETE from modx_ecomm_lists_options ";
		$qry .= "where id=$listoptionid";
		$result=mysql_query($qry) or die ("MYSQL ERROR: " . mysql_error());
	}

/**
 * This function is designed to interface with rendertoption to produce ALL of the options
 * associated with an item
 * 
 * @param	itemid			=	ID of the item to find options for
 */
	function populateoptionsarea($itemid, $layout){
		$qry = 'SELECT options_id from modx_ecomm_items_options where item_id=' . $itemid . " ORDER BY id";
		$result= mysql_query($qry);
		$opts="";
		$hiddenopts="";
		while($row=mysql_fetch_row($result)){
			$qry = 'SELECT name, renderas from modx_ecomm_options where id=' . $row[0];
			$res=mysql_query($qry);
			$rw=mysql_fetch_row($res);
			$hiddenopts.= $rw[0] . ":" . $rw[1] . "||";
			$opts.= "<div class=\"itemoptions\" style=\"float:right; width: 60%; padding-bottom: 5px; padding-top: 5px;\">" . renderoption($itemid, $rw[0]) . "</div>";
			$opts.= "<div class=\"itemoptionslabel\" style=\"float:left; width: 40%\">" . $rw[0] . ":  </div>";
		}
		$trimmedopts = substr($hiddenopts, 0, strlen($hiddenopts)-2);
		echo '<input type="hidden" id="itemoptsstr" name="itemoptsstr" value="' . $trimmedopts . '" />';
		echo '<input type="hidden" id="qtyfield" name="qtyfield" value="1" />';
		return $opts;		
	}

//TODO: Fix Item Quantity to validate based on type of quantity required
/**
 * This is a function designed to produce a qty field with the correct validation (integer or float)
 * 
 * @param		itemid		=	ID of the item to produce a box for
 */
	function display_quantity($itemid){
         echo '<input type="text" id="qtytoenter" name="qtytoenter" size=2>';	
	}
/*
 * This method is designed to render an option when it receives the itemid and name
 * of the option.  It allows you to choose from several different HTML entities for
 * display
 * 
 * RADIO, SELECT, MULTI, CHECK, TEXTAREA, TEXT
 * 
 * NOTE: These are stored in the database header table for the option.
 * 
 * @param		optionname	=	Name of the option to render
 * @param		itemid		=	ID of the item to get options for
 */
    function renderoption($itemid, $optionname){
        $optioninfo=getoptionbyname($optionname);
		$opts=getlistoptions($optioninfo['listid']);
        $type=strtolower($optioninfo['renderas']);
        $opt="";

        if (($type=="radiobutton") || ($type=="radio")){
            $i=0;
            while ($opts['name'][$i] != null){
                if ($opts['name'][$i]==$optioninfo['default']){$sel="selected";}
                $opt .= "<input $sel class=\"" . $optioninfo['htmlclass'] . "\" type=\"radio\" id=\"" . $optionname .  "\" name=\"" . $optionname . "\" value=\"" . $opts['id'][$i] . "\" OnClick=\"updateprice('" . $optionname . "', " . $opts['priceoffset'][$i] . ", 'radio');\">" . $opts['name'][$i] .  "  " . priceoffsetdisplay($opts['priceoffset'][$i]) . "<br />\n";
                $i++;
                $sel="";
            }

        } else if (($type=="dropdown") || ($type=="select") || ($type=="drop")){
            $opt .= "<select id=\"" . $optionname . "\" name=\"" . $optionname . "\" class=\"" . $optioninfo['htmlclass'] . "\">\n";
            $i=0;
            while ($opts['name'][$i] != null){
                if ($opts['name'][$i]==$optioninfo['default']){$sel="selected";}
                $opt .= "\t<option $sel class=\"" . $optionname . "-row-" . $i . "\" value=\"" . $opts['id'][$i]. "\" OnClick=\"document.getElementById('" . $optionname . "').selectedIndex=" . $i . "; updateprice('" . $optionname . "', " . $opts['priceoffset'][$i] . ", 'drop');\">" . $opts['name'][$i] . "  " . priceoffsetdisplay($opts['priceoffset'][$i]) . "</option>\n";
                $i++;
                $sel="";
            }
            $opt .= "</select>\n";

        } else if (($type=="multiselect") || ($type=="multi")){
            $opt .= "<select id=\"" . $optionname . "\" name=\"" . $optionname . "\" class=\"" . $optioninfo['htmlclass'] . "\" multiple size=" . $optioninfo['size'] . ">\n";
            $i=0;
            while ($opts['name'][$i] != null){
                if ($opts['name'][$i]==$optioninfo['default']){$sel="selected";}

                $opt .= "\t<option $sel id=\"" . $optionname . "-" . $i . "\" value=\"" . $opts['id'][$i] ."\" OnClick=\"updateprice('" . $optionname . "', " . $opts['priceoffset'][$i] . ", 'multi' );\">" . $opts['name'][$i] .  "  " . priceoffsetdisplay($opts['priceoffset'][$i]) . "</option><br />\n";
                $i++;
                $sel="";
            }
            $opt .= "</select>\n";

        } else if (($type=="checkbox") || ($type=="check")){
            $i=0;
            while ($opts['name'][$i] != null){
                if ($opts['name'][$i]==$optioninfo['default']){$sel="checked";}

                $opt .= "<input $sel id=\"" . $optionname . "-" . $i . "\" class=\"" . $optioninfo['htmlclass'] . "\" name=\"" . $optionname . "\" type=\"checkbox\" value=\"" . $opts['id'][$i] . "\" OnClick=\"updateprice('" . $optionname . "', " . $opts['priceoffset'][$i] . ", 'check');\">" . $opts['name'][$i] . "  " . priceoffsetdisplay($opts['priceoffset'][$i]) . "<br />\n";
                $i++;
                $sel="";
            }

        } else if (($type=="textarea")) {
            $i=0;
            $opt .= "<textarea id=\"" . $optionname . "\" class=\"" . $optioninfo['htmlclass'] . "\" name=\"" . $optionname . "\" rows=\"" . $optioninfo['length'] . "\" cols=\"" . $optioninfo['size'] . "\">\n";
            $opt .= "</textarea>";

        } else if (($type=="text")){
            $i=0;
            $opt .= "<input type=\"text\" id=\"" . $optionname . "\" class=\"" . $optioninfo['htmlclass'] . "\" name=\"" . $optionname . "\" size=" . $optioninfo['size'] . "/>";
        }

        return $opt;
    }

/*
 * This is a helper function to decide whether to display price offsets or not.
 * 
 * The reason I broke this method out is so that it could be called in-line
 * when I render the option and so that it can be overridden easily by developers
 * like the one who is probably reading this.
 * 
 * @param		poffset			=	Price offset sent in
 * 
 * TODO
 * @return
 */
	function priceoffsetdisplay($poffset){
		$num=number_format($poffset,2);
		
		if ($num != 0.00){
			return "&nbsp;&nbsp;" . $num;
		} 
	}

/*
 * This is designed to return an associative array of information about a customer, including their modX user information
 * 
 * @param	id		=	ID of the customer in modx_ecomm_customers
 */
	function getcustinfo($id){
		$qry = "SELECT fname, lname, addr1, addr2, city, state, zip, phone_1, phone_2, ext_1, ext_2, fax, custid, companyname from modx_ecomm_customers where id=$id";
		$result=mysql_query($qry) or die ("COULD NOT RETRIEVE USER: " . mysql_error());
		$row = mysql_fetch_row($result);
		
		$cust['id'] = $id;
		$cust['fname'] = $row[0];
		$cust['lname'] = $row[1];
		$cust['addr1'] = $row[2];
		$cust['addr2'] = $row[3];
		$cust['city'] = $row[4];
		$cust['state'] = $row[5];
		$cust['zip'] = $row[6];
		$cust['phone_1'] = $row[7];
		$cust['phone_2'] = $row[8];
		$cust['ext_1'] = $row[9];
		$cust['ext_2'] = $row[10];
		$cust['fax'] = $row[11];
		$cust['custid'] = $row[12];
		$cust['companyname'] = $row[13];
		
		$qry = "SELECT username, password from modx_web_users where id=" . $row[12];
		$result=mysql_query($qry) or die ("COULD NOT RETRIEVE CUSTWEB: " . mysql_error());
		$row=mysql_fetch_row($result);
		$cust['username'] = $row[0];
		$cust['password'] = $row[1];
		
		$qry = "SELECT failedlogincount, blocked, blockeduntil, logincount, comment from modx_web_user_attributes where internalKey=" . $cust['custid'];
		$result=mysql_query($qry) or die ("COULD NOT GET BLOCK STATUS: " . mysql_error());
		$row=mysql_fetch_row($result);
		$cust['failedlogincount'] = $row[0];
		$cust['blocked'] = $row[1];
		$cust['blockeduntil'] = $row[2];
		$cust['logincount'] = $row[3];
		$cust['commentssection'] = $row[4];
		
		return $cust;
	}

/*
 *  This is designed to check whether there is a user in the system who is already using the username
 *  that a person is trying to use to sign up for an account;
 * 
 *  @username
 * 
 * This verifies ModX's database before attempting to add a user
 * 
 * NOTE:  Returns true if a duplicate user is found...otherwise it returns false
 */

	function checkusername($username){
		$qry = "SELECT username from modx_web_users";
		$result=mysql_query($qry) or die ("FETCH EXISTING MODX USERS ERROR: " . mysql_error());
		
		$response="FALSE";
		
		for ($i=0; $i < mysql_num_rows($result); $i++){
			$row=mysql_fetch_row($result);
			if ($row[0] == strtolower($username)){
				return "TRUE";	
			}
		}
		return $response;
	}

/*
 * This is designed to check whether there is a userer in the system who already has the email address
 * that a person is trying to user to sign up for an account;
 * 
 * @email
 * 
 * This verified ModX's database before attempting to add a new user
 * 
 * NOTE:  Returns true if a duplicate user email is found...otherwise it returns false
 */
	function checkemail($email){
		$qry = "SELECT email from modx_web_user_attributes";
        $result=mysql_query($qry) or die ("FETCH EXISTING MODX USERS ERROR: " . mysql_error());
		
	    $response="FALSE";
		
		if (ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
        	for ($i=0; $i < mysql_num_rows($result); $i++){
	        	$row=mysql_fetch_row($result);
            	if ($row[0] == strtolower($email)){
               		return "TRUE";
            	}
        	}
		} else {
			$response="INVALID";	
		}
        	return $response;
	}


/*
 * This function is designed to update customer info stored in a couple tables within ModX
 * 
 * @param	id					=	Customer ID in MOdX Ecommerce
 * @param	intkey				=	Internal ModX ID
 * 
 * //SELF EXPLANATORY - BASIC CUST INFO
 * @param	companyname
 * @param	fname
 * @param 	lname
 * @param	addr1
 * @param 	addr2
 * @param	city
 * @param	state
 * @param	zip
 * @param 	phone_1
 * @param   phone_2
 * @param	ext_1
 * @param 	ext_2
 * @param 	fax
 * 
 * @param 	username			=	username of the person
 * @param	password			=	hex md5 hash of the new password
 * 
 * @param	logincount			=	Number of logins
 * @param	failedlogincount	=	Number of times a user has failed during login (Set this to 0 too to unlock an account)
 * @param	blocked				=	BOOL (0=false || 1=true)
 * @param	blockeduntil		=	TimeStanp of sorts telling when a failed user can log in again (Set to 0 to reset)
 * @param	comment				=	Comment about the customer (Could be anything)
 */
	function updatecustinfo($id, $intkey, $companyname, $fname, $lname, $addr1, $addr2, $city, $state, $zip, $phone_1, $phone_2, $ext_1, $ext_2, $fax, $username, $password, $logincount, $failedlogincount, $blocked, $blockeduntil, $comment){
		$qry  = "UPDATE modx_ecomm_customers set ";
		$qry .= "companyname=\"$companyname\", ";
		$qry .= "fname=\"$fname\", ";
		$qry .= "lname=\"$lname\", ";
		$qry .= "addr1=\"$addr1\", ";
		$qry .= "addr2=\"$addr2\", ";
		$qry .= "city=\"$city\", ";
		$qry .= "state=\"$state\", ";
		$qry .= "zip=\"$zip\", ";
		$qry .= "phone_1=\"$phone_1\", ";
		$qry .= "phone_2=\"$phone_2\", ";
		$qry .= "ext_1=\"$ext_1\", ";
		$qry .= "ext_2=\"$ext_2\", ";
		$qry .= "fax=\"$fax\" ";
		$qry .= "where id=$id";
		$result=mysql_query($qry) or die ("COULD NOT UPDATE BASE INFO" . mysql_error());
		
		if ($password != "721f9cc2462b656dfffea297f77e9f2e"){ //(the md5 of NOTAVALIDPASSWORD
			$qry = "UPDATE modx_web_users set ";
			$qry .= "username=\"$username\", ";
			$qry .= "password=\"$password\" ";
			$qry .= "where id=$intkey";
			$result=mysql_query($qry) or die ("COULD NOT UPDATE USERNAME/PW" . mysql_error());
		}
		
		$qry  = "UPDATE modx_web_user_attributes set ";
		$qry .= "logincount=$logincount, ";
		$qry .= "failedlogincount=$failedlogincount, ";
		$qry .= "blocked=$blocked, ";
		$qry .= "blockeduntil=$blockeduntil, ";
		$qry .= "comment=\"$comment\" ";
		$qry .= "where internalKey=$intkey";
		$result=mysql_query($qry) or die ("COULD NOT UPDATE WEB USER ATTRIB" . mysql_error());
	}

/*
 * This is designed to return the details of an order
 * 
 * @param		id		=	Order ID
 */
	function getorderinfo($id){
		$qry = "SELECT id, pay_id, cust_id, totshipping, tothandling, tax, total, subtotal, paymentApproved, authCode, ponumber, status, orderitems, created, updated, shipfname, shiplname, shipaddr1, shipaddr2, shipcity, shipstate, shipzip, shipphone, shipext from modx_ecomm_order_header where id=$id";
		$result =mysql_query($qry);
		$row= mysql_fetch_row($result);
		  
		$ordinfo['id'] = $row[0];
		$ordinfo['pay_id'] = $row[1];
		$ordinfo['cust_id'] = $row[2];
		$ordinfo['totshipping'] = $row[3];
		$ordinfo['tothandling'] = $row[4];
		$ordinfo['tax'] = $row[5];
		$ordinfo['total'] = $row[6];
		$ordinfo['subtotal'] = $row[7];
		$ordinfo['paymentApproved'] = $row[8];
		$ordinfo['authCode'] = $row[9];
		$ordinfo['ponumber'] = $row[10];
		$ordinfo['status'] = $row[11];
		$ordinfo['orderitems'] = $row[12];
		$ordinfo['created'] = $row[13];
		$ordinfo['updated'] = $row[14];
		$ordinfo['shipfname'] = $row[15];		
		$ordinfo['shiplname'] = $row[16];		
		$ordinfo['shipaddr1'] = $row[17];		
		$ordinfo['shipaddr2'] = $row[18];		
		$ordinfo['shipcity'] = $row[19];		
		$ordinfo['shipstate'] = $row[20];		
		$ordinfo['shipzip'] = $row[21];		
		$ordinfo['shipphone'] = $row[22];		
		$ordinfo['shipext'] = $row[23];		
		$qry = "SELECT name from modx_ecomm_pay_gateways where id=" . $ordinfo['pay_id'];
		$result=mysql_query($qry);
		$row=mysql_fetch_row($result);
		
		$ordinfo['payment_name'] = $row[0];
		
		$qry = "SELECT fname, lname, addr1, addr2, city, state, zip, phone_1, ext_1, phone_2, ext_2, fax, companyname, custid from modx_ecomm_customers where id=" . $ordinfo['cust_id'];
		$result=mysql_query($qry);
		$row=mysql_fetch_row($result);
		
		$ordinfo['fname'] = $row[0];
		$ordinfo['lname'] = $row[1];
		$ordinfo['addr1'] = $row[2];
		$ordinfo['addr2'] = $row[3];
		$ordinfo['city'] = $row[4];
		$ordinfo['state'] = $row[5];
		$ordinfo['zip'] = $row[6];
		$ordinfo['phone_1'] = $row[7];
		$ordinfo['ext_1'] = $row[8];
		$ordinfo['phone_2'] = $row[9];
		$ordinfo['ext_2'] = $row[10];
		$ordinfo['fax'] = $row[11];
		$ordinfo['companyname'] = $row[12];
		$ordinfo['modxcustid'] = $row[13];
		
		$qry = "select email from modx_web_user_attributes where id=" . $ordinfo['modxcustid'];
		$result=mysql_query($qry);
		$row=mysql_fetch_row($result);
		$ordinfo['email'] = $row[0];
		return $ordinfo;
	}

/*
 * This is designed to return order maintenance statistics
 */
	function getorderstats(){
		$qry = "SELECT id, status from modx_ecomm_order_header";
		$result=mysql_query($qry);
		
		$ordstat="";
		
		$ordstat['neworders'] = 0;
		$ordstat['cancelledorders'] = 0;
		$ordstat['updatedorders'] = 0;
		$ordstat['processedorders'] = 0;
		$ordstat['errororders'] = 0;
		$ordstat['backorders'] = 0;
		$ordstat['shippedorders'] = 0;
		$ordstat['totalorders'] = 0;
		
		
		while ($row=mysql_fetch_row($result)){
			switch($row[1]){
				case "NEW":
					$ordstat['neworders']++;
				break;
				
				case "CANCELLED":
					$ordstat['cancelledorders']++;				
				break;
				
				case "UPDATED":
					$ordstat['shippedorders']++;
				break;
				
				case "PROCESSING":
					$ordstat['processedorders']++;
				break;
				
				case "SHIPPED":
					$ordstat['shippedorders']++;
				break;
				
				case "BACKORDERED":
					$ordstat['backorders']++;
				break;
				
				case "ERROR":
					$ordstat['errororders']++;
				break;
			}
			$ordstat['totalorders']++;
		}		
		return $ordstat;
	}

/*
 * This is designed to return item maintenance statistics
 */
	function getitemstats(){
		$qry = "SELECT id, status from modx_ecomm_items_audit";
		$result=mysql_query($qry);
		
		$itemstat="";
		
		$itemstat['newitems'] = 0;
		$itemstat['currentitems'] = 0;
		$itemstat['deleteditems'] = 0;
		$itemstat['updateditems'] = 0;
		$itemstat['newitems'] = 0;
		$itemstat['totalitems'] = 0;
		
		
		while ($row=mysql_fetch_row($result)){
			switch($row[1]){
				case "new":
					$itemstat['newitems']++;
				break;
				
				case "current":
					$itemstat['currentitems']++;
				break;
				
				case "updated":
					$itemstat['updateditems']++;
				break;
				
			 	case "deleted":
					$itemstat['deleteditems']++;
				break;
				
				case "current":
					$itemstat['currentitems']++;
			}
			$itemstat['totalitems']++;
		}		
		return $itemstat;
	}

/*
 * This method will get the names of the options which are associated with an item
 *  
 * @param	itemid		=	id of the item
 */
	function getoptionsforitem($itemid){
		$ = "SELECT id, item_id, lists_id, name, renderas, htmlclass, size, length, default, deflt from modx_ecomm_items_options where item_id=\"\"";
	}

/*
 * This function will check whether a user is a valid modx user and then make sure that
 * they have an ecomm account.  If they don't have either, false is returned.  If they 
 * DO have both, true is returned.  If they don't have an ecomm account, I will make one
 * for them (simple update of modx_ecomm_customers
 * 
 * @param	sessionid		=	Session ID of the user
 * @param	webshortname	=	ModX username logged in
 * @param	webinternalkey	=	ModX mySQL ID of the user logged in
 * @param	webemail		=	ModX email of the user logged in
 * @param	webvalid		=	Not sure, but I won't handle it for now.  I believe
 * 								(without research) that it is some form of session var
 * 								to identify the user as being a valid web user.  Perhaps
 * 								reversible encryption?
 * @param	webuser			=	Not sure, but I won't handle it for now.  I believe
 * 								(without research) that it is some form of session var
 * 								to identify the user as being a valid web user.  Perhaps
 * 								this is done with reversible encryption since I don't see
 * 								a translation table of sorts in the modx_ database.
 */
	function checklogin($sessionid, $webshortname, $webinternalkey, $webemail, $webvalid, $webuser){
		// Check for valid data
		if ($webinternalkey!="" && $sessionid!="" && $webshortname!=""){
			$qry = "SELECT username, password from modx_web_users where id=$webinternalkey";
			$result=mysql_query($qry);
			$row=mysql_fetch_row($result);
		
			$dbuser = $row[0];
			$dbpass = $row[1];
			// Check that the dbuser matches the clientside username
			if ($dbuser == $webshortname){
				$qry = "SELECT email, sessionid, phone, mobilephone, country, state, zip, fax, fullname from modx_web_user_attributes where internalKey=$webinternalkey";
				$result=mysql_query($qry);
				$row=mysql_fetch_row($result);
				
				$email=$row[0];
				$dbsession = $row[1];
				$modxphone = $row[2];
				$modxmobilephone = $row[3];
				$modxcountry = $row[4];
				$modxstate = $row[5];
				$modxzip = $row[6];
				$modxfax = $row[7];
				$modxfullname = $row[8];
				  
				// Check that client email and session info matches what is in the database
				if ($email==$webemail && $dbsession==$sessionid){
					// OK now we know the client is authenticated for ModX
					// Lets make sure they have an ecomm account
					$qry = "SELECT * from modx_ecomm_customers where custid=$webinternalkey";
					$result=mysql_query($qry);
					if (mysql_num_rows($result) > 0){
						// YAY, the user is in both systems, you may pass...
						return "MATCH";
					} else {
						// In this case, the user might have existed pre-ecomm days, so 
						// we need to add their record
						if ($modxcountry==223){
							$modxcountry="USA";	
						}{
							$modxcountry="";	
						}// Sorry, everyone else will have to add their own to this
						$qry  = "INSERT into modx_ecomm_customers (fname, state, country, zip, phone_1, phone_2, fax, custid) ";
						$qry .= " values (";
						$qry .= "\"$modxfullname\", \"$modxstate\", \"$modxcountry\", \"$modxzip\", \"$modxphone\", \"$modxmobilephone\", \"$modxfax\", $webinternalkey)";
						$result = mysql_query($qry) or die ("ERROR: " . mysql_error());
						return "MATCH";
					}
					
				} else {
					// clientside email matches a record, but their sessionid doesn't match the db value
					return "STALESESSION";
				}
			}else {
				// clientside username didn't match what was in the database
				return "TRYAGAINORCREATE";
			}
		} else {
			// clientside didn't pass us valid data
			return "NODATA";
		}
	}

/*
 * This is designed to grab the all options and then display only the ones that are not 
 * already in use on the item.
 * 
 * @param	itemid		=	Item ID of the item we are retrieving options for
 */
    function getallitemoptions($itemid){
		$qry = "SELECT options_id from modx_ecomm_items_options where item_id=$itemid";
		$result=mysql_query($qry);
		
		// Get Chosen Options from DB
		$i=0;
		$chosen="";
		while($row=mysql_fetch_row($result)){
			$chosen[$i]=$row[0];
			$i++;
		}
		
        $qry = "SELECT id, name from modx_ecomm_options";
        $result=mysql_query($qry);

		// Get All Options in DB
		$i=0;
		$all="";
		while($row=mysql_fetch_row($result)){
			$all[$i]['id']=$row[0];
			$all[$i]['name']=$row[1];
			$i++;				
		}
		
		// Only display those options which are not chosen
       	for ($k=0; $k < $i; $k++){
			$alreadyused='false';
			for($l=0; $l < sizeof($chosen); $l++){
				if ($all[$k]['id']==$chosen[$l]){
					$alreadyused='true';	
				}
			}
			
			if ($alreadyused=='false'){
	            echo "<div id=\"alloptdiv_" . $all[$k]['id'] .  "\" style=\"color: white; background-color: #1A496D; padding:5px; border-style: solid; border-width: 2px; border-color: #518BFF; margin: 3px; margin-left: 10px; margin-right: 10px;\" class=\"alloptdivs\">" . $all[$k]['name'] . "</div>";
			}
        }
	}		

/*
 * This is designed to grab the options already associated with the item
 * 
 * @param	itemid		=	Item ID of the item we are retrieving options for
 */
	function getallchosenoptions($itemid){
		$qry = "SELECT options_id from modx_ecomm_items_options where item_id=$itemid ORDER BY id";
		$result=mysql_query($qry);

        while($r=mysql_fetch_row($result)){
			$qry = "SELECT id, name from modx_ecomm_options where id=" . $r[0];
			$res = mysql_query($qry);
			$row=mysql_fetch_row($res);
			
            echo "<div id=\"alloptdiv_" . $row[0] . "\" style=\"color: white; background-color: #1A496D; padding:5px; border-style: solid; border-width: 2px; border-color: #518BFF; margin: 3px; margin-left: 10px; margin-right: 10px;\" class=\"alloptdivs\">" . $row[1] . "</div>";
        }		
	}

/*
 *  This is designed to return all content templates from ModX
 */
	function gettemplates($id){
		$qry = "SELECT templatename, id from modx_site_templates";
		
		$result=mysql_query($qry);

		echo "<select tabindex=\"10\" id=\"templateid\" name=\"templateid\" >";		
		
		while ($row=mysql_fetch_row($result)){
			if ($id==$row[1]){
				$enbl="SELECTED";
			}else {
				$enbl="";
			}
		    echo "<option $enbl name=\"" . $row[0] . "\" value=\"" . $row[1] . "\">" . $row[0] . "</option>";
		}

		echo "</select>";
	}

/*
 *  This is designed to return all chunks from ModX to use as
 *  content templates
 */
	function getchunks(){
		$qry = "SELECT name, id from modx_site_htmlsnippets";
		
		$result=mysql_query($qry);

		echo "<select onchange=\"updatecontenttemplate();\" tabindex=\"11\" id=\"chunkid\" name=\"chunkid\"  >";		
		echo "<option name=\"Default\" value=\"NONE\">Choose Content Template:</option>";
		while ($row=mysql_fetch_row($result)){
			echo "<option name=\"" . $row[0] . "\" value=\"" . $row[1] . "\">" . $row[0] . "</option>";
		}
		echo "</select>";
	}

/*
 * This method is designed to return the value of a chunk (HTML code)
 * 
 * This is mainly used for the Administrative Interface to choose the template
 * to use for a product page.
 * 
 * @param	chunkid		=	ID of the chunk to pull from the database
 */
	function getchunkcontent($chunkid){
		$qry = "SELECT snippet from modx_site_htmlsnippets where id=\"$chunkid\"";
		$result=mysql_query($qry);
		$row = mysql_fetch_row($result);
		echo $row[0];
	}

/*
 * This function is designed to return an array of customer information based on 
 * their webInternalKey
 * 
 * @param		webinternalkey		=	This is the modx webInternalKey
 */

	function getcustomerinfo($webinternalkey){
		$qry  = "SELECT fname, lname, addr1, addr2, city, state, ";
		$qry .= "zip, phone_1, phone_2, ext_1, ext_2, fax, companyname, ";
		$qry .= "country from modx_ecomm_customers ";
		$qry .= "where custid=$webinternalkey";
		
		$result=mysql_query($qry);
		$row= mysql_fetch_row($result);
		
		$ret['fname']=$row[0];
		$ret['lname']=$row[1];
		$ret['addr1']=$row[2];
		$ret['addr2']=$row[3];
		$ret['city']=$row[4];
		$ret['state']=$row[5];
		$ret['zip']=$row[6];
		$ret['phone_1']=$row[7];
		$ret['phone_2']=$row[8];
		$ret['ext_1']=$row[9];
		$ret['ext_2']=$row[10];
		$ret['fax']=$row[11];
		$ret['companyname']=$row[12];
		$ret['country']=$row[13];
		
		return $ret;
	}

/*
 * This function is designed to create an order header with the details that the user provides
 * 
 * It updates the fields found in the cart header for billing information and shipping information
 * 
 * @param	TOO MANY TO LIST:  It takes in the session id and all POST data for billing
 * 							   and shipping information
 */
	function updatecartforcheckout($sessionid, $emailbilling, $fnamebilling, $lnamebilling, $addr1billing, $addr2billing, $citybilling, $statebilling, $zipbilling, $phonebilling, $extbilling, $faxbilling, $companybilling, $companyship, $fnameship, $lnameship, $addr1ship, $addr2ship, $cityship, $stateship, $zipship, $phoneship, $extship){
		$qry  = "UPDATE modx_ecomm_cart_header ";
		$qry .= "set ";
		$qry .= "fname=\"$fnamebilling\", ";
		$qry .= "lname=\"$lnamebilling\", ";
		$qry .= "addr1=\"$addr1billing\", ";
		$qry .= "addr2=\"$addr2billing\", ";
		$qry .= "city=\"$citybilling\", ";
		$qry .= "state=\"$statebilling\", ";
		$qry .= "zip=\"$zipbilling\", ";
		$qry .= "phone_1=\"$phonebilling\", ";
		$qry .= "ext_1=\"$extbilling\", ";
		$qry .= "fax=\"$faxbilling\", ";
		$qry .= "company=\"$companybilling\", ";
		$qry .= "shipcompany=\"$companyship\", ";
		$qry .= "shipfname=\"$fnameship\", ";
		$qry .= "shiplname=\"$lnameship\", ";
		$qry .= "shipaddr1=\"$addr1ship\", ";
		$qry .= "shipaddr2=\"$addr2ship\", ";
		$qry .= "shipcity=\"$cityship\", ";
		$qry .= "shipstate=\"$stateship\", ";
		$qry .= "shipzip=\"$zipship\", ";
		$qry .= "shipphone=\"$phoneship\", ";
		$qry .= "shipext=\"$extship\" ";
		$qry .= "where session_id=\"$sessionid\"";
		$result=mysql_query($qry) or die ("UPDATE CART CUST INFO: " . mysql_error());
	}
?>